package com.ruoyi.web.controller.cs;

import java.math.BigDecimal;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.CheckSwitch;
import com.ruoyi.common.core.controller.BasicsController;
import com.ruoyi.common.core.domain.Response;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.ResponsePageInfo;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.cs.domain.TBattleUser;
import com.ruoyi.cs.domain.TGoods;
import com.ruoyi.cs.domain.vo.TBoxVo;
import com.ruoyi.cs.mapper.TBackpackMapper;
import com.ruoyi.cs.mapper.TRechargeMapper;
import com.ruoyi.cs.mapper.TWarReceiveMapper;
import com.ruoyi.cs.service.ITGoodsService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.cs.domain.TBox;
import com.ruoyi.cs.service.ITBoxService;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;

/**
 * 箱子信息Controller
 * 
 * @author ruoyi
 * @date 2021-03-25
 */
@Api(tags = {"箱子信息管理"})
@RestController
@RequestMapping("/cs/box")
@SuppressWarnings("all")
public class TBoxController extends BasicsController
{
    private static final Logger log = LoggerFactory.getLogger(TBoxController.class);
    @Autowired
    private ITBoxService tBoxService;
    @Autowired
    private ITGoodsService tGoodsService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private TRechargeMapper tRechargeMapper;
    @Autowired
    private TBackpackMapper backpackMapper;
    @Autowired
    private TWarReceiveMapper tWarReceiveMapper;

    /**
     * 后台查询箱子信息列表
     */
    @PreAuthorize("@ss.hasPermi('cs:box:listBack')")
    @ApiOperation("后台查询箱子信息列表")
    @RequestMapping(name="后台查询箱子信息列表",value="listBack",method = RequestMethod.POST)
    public ResponsePageInfo<TBoxVo> listBack(@RequestBody TBoxVo tBoxVo)
    {
        startPage(tBoxVo.getPageNum(),tBoxVo.getPageSize());
        tBoxVo.setBackStage(Constants.BACKSTAGE);
        List<TBoxVo> list = tBoxService.boxListBack(tBoxVo);
        return toResponsePageInfo(list);
    }

    @PreAuthorize("@ss.hasPermi('cs:box:boxCount')")
    @ApiOperation("箱子统计信息")
    @RequestMapping(name="箱子统计信息",value="boxCount",method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startTime",value = "开始时间" ,dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "endTime",value = "结束时间" , dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "boxType",value = "箱子类型 0普通箱子 1对战箱子" , dataType = "String", paramType = "query", required = false),
    })
    public Response<Map> boxCount(String startTime, String endTime,String boxType)
    {
        try {
            return Response.success(tBoxService.boxCount(startTime, endTime,boxType));
        } catch (Exception e) {
            log.error("箱子统计信息:{}",e.getMessage());
            return Response.fail(e.getMessage());
        }
    }

    /**
     * 新增箱子信息
     */
    @PreAuthorize("@ss.hasPermi('cs:box:add')")
    @ApiOperation("新增箱子信息")
    @RequestMapping(name="新增箱子信息",value="add",method = RequestMethod.POST)
    @Log(title = "新增箱子信息", businessType = BusinessType.INSERT)
    public Response<Integer> add(@RequestBody TBox tBox)
    {
        try {
            return toResponse(tBoxService.insertTBox(tBox));
        } catch (Exception e) {
            log.error("新增箱子信息异常:{}",e.getMessage());
            return Response.fail(e.getMessage());
        }
    }

    /**
     * 修改箱子信息
     */
    @PreAuthorize("@ss.hasPermi('cs:box:edit')")
    @ApiOperation("修改箱子信息")
    @RequestMapping(name="修改箱子信息",value="edit",method = RequestMethod.POST)
    @Log(title = "修改箱子信息", businessType = BusinessType.UPDATE)
    public Response<Integer> edit(@RequestBody TBox tBox)
    {
        try {
            return toResponse(tBoxService.updateTBox(tBox));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("修改箱子信息异常:{}",e.getMessage());
            return Response.fail(e.getMessage());
        }
    }
    /**
     * 箱子饰品列表
     * @param tBox
     * @return
     */
    @ApiOperation("根据箱子ID获取对应的饰品列表")
    @RequestMapping(name="根据箱子ID获取对应的饰品列表",value="boxGoodsList",method = RequestMethod.POST)
    public ResponsePageInfo boxGoodsList(@RequestBody TBox tBox)
    {
            startPage(tBox.getPageNum(),tBox.getPageSize());
            List<TGoods> list  = tBoxService.GoodsListBox(tBox.getBoxId());
            TBox box = tBoxService.getInfoTbox(tBox.getBoxId());
            return getDataTableObj(box,list);
    }
    /**
     * 修改箱子首开状态
     */
    @PreAuthorize("@ss.hasPermi('cs:box:editfirst')")
    @ApiOperation("修改箱子首开状态")
    @RequestMapping(name="修改箱子首开状态",value="editfirst",method = RequestMethod.POST)
    @Log(title = "箱子信息", businessType = BusinessType.UPDATE)
    public Response<Integer> editfirst(@RequestBody TBox tBox)
    {
        try {
            return toResponse(tBoxService.updateTBoxFirstStatus(tBox));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("修改箱子首开状态异常:{}",e.getMessage());
            return Response.fail(e.getMessage());
        }
    }
    /**
     * 删除箱子信息
     */
    @PreAuthorize("@ss.hasPermi('cs:box:remove')")
    @ApiOperation("删除箱子信息")
    @RequestMapping(name="删除箱子信息",value="remove",method = RequestMethod.GET)
    @Log(title = "箱子信息", businessType = BusinessType.DELETE)
    @ApiImplicitParam(name = "boxIds",value = "需要删除的箱子信息ID,多个以：“,”分割" ,dataType = "String", paramType = "query", required = false)
    public Response<Integer> remove(String boxIds)
    {
        try {
            if (StringUtils.isNotEmpty(boxIds)) {
                String[] ids = boxIds.split(",");
                int row = tBoxService.deleteTBoxByIds(ids);
                if (row == Constants.FAILCODE) {
                    return Response.fail(Constants.FAILCODE,"选中箱子下存在饰品，请先删除饰品!");
                }
                return toResponse(row);
            }else{
                return Response.fail(Constants.FAILCODE,"参数不能为空!");
            }
        } catch (Exception e) {
            log.error("删除箱子信息异常:{}",e.getMessage());
            return Response.fail(e.getMessage());
        }
    }
    /**
     * 停用箱子信息
     */
    @PreAuthorize("@ss.hasPermi('cs:box:stop')")
    @ApiOperation("停用箱子信息")
    @RequestMapping(name="停用箱子信息",value="stop",method = RequestMethod.GET)
    @Log(title = "箱子信息", businessType = BusinessType.STOP)
    @ApiImplicitParam(name = "boxIds",value = "需要停用的箱子信息ID,多个以：“,”分割" ,dataType = "String", paramType = "query", required = false)
    public Response<Integer> stop(String boxIds)
    {
        try {
            if (StringUtils.isNotEmpty(boxIds)) {
                String[] ids = boxIds.split(",");
                int row = tBoxService.bacthStopTBox(ids);
                if (row == Constants.FAILCODE) {
                    return Response.fail(Constants.FAILCODE,"选中箱子下存在可用饰品，请先停用饰品!");
                }
                return toResponse(row);
            }else{
                return Response.fail(Constants.FAILCODE,"参数不能为空!");
            }
        } catch (Exception e) {
            log.error("停用箱子信息异常:{}",e.getMessage());
            return Response.fail(e.getMessage());
        }
    }
    /**
     * 启用箱子信息
     */
    @PreAuthorize("@ss.hasPermi('cs:box:enable')")
    @ApiOperation("启用箱子信息")
    @RequestMapping(name="启用箱子信息",value="enable",method = RequestMethod.GET)
    @Log(title = "箱子信息", businessType = BusinessType.ENABLE)
    @ApiImplicitParam(name = "boxIds",value = "需要启用的箱子信息ID,多个以：“,”分割" ,dataType = "String", paramType = "query", required = false)
    public Response enable(String boxIds)
    {
        try {
            if (StringUtils.isNotEmpty(boxIds)) {
                String[] ids = boxIds.split(",");
                return tBoxService.bacthEnableTBox(ids);
            }else{
                return Response.fail(Constants.FAILCODE,"参数不能为空!");
            }
        } catch (Exception e) {
            log.error("启用箱子信息异常:{}",e.getMessage());
            return Response.fail(e.getMessage());
        }
    }

    /**
     * 开箱统计
     */
    @PreAuthorize("@ss.hasPermi('cs:box:unpackingCount')")
    @ApiOperation("开箱统计")
    @RequestMapping(name="开箱统计",value="unpackingCount",method = RequestMethod.GET)
    public Response<Map> unpackingCount()
    {
        try {
            return tBoxService.unpackingCount();
        } catch (Exception e) {
            log.error("新增箱子信息异常:{}",e.getMessage());
            return Response.fail(e.getMessage());
        }
    }

    /**
     * 后台开箱统计列表
     */
    @PreAuthorize("@ss.hasPermi('cs:box:boxListBackCount')")
    @ApiOperation("后台开箱统计列表")
    @RequestMapping(name = "后台开箱统计列表", value = "boxListBackCount", method = RequestMethod.POST)
    public ResponsePageInfo<TBoxVo> boxListBackCount(@RequestBody TBoxVo tBoxVo) {
        startPage(tBoxVo.getPageNum(), tBoxVo.getPageSize());
        tBoxVo.setBackStage(Constants.BACKSTAGE);
        List<TBoxVo> list = tBoxService.boxListBackCount(tBoxVo);
        return toResponsePageInfo(list);
    }

    /**
     * 箱子列表（不包含最贵饰品信息）
     */
    @PreAuthorize("@ss.hasPermi('cs:box:boxListBackCount')")
    @ApiOperation("箱子列表（不包含最贵饰品信息）")
    @RequestMapping(name = "箱子列表（不包含最贵饰品信息）", value = "queryTBoxList", method = RequestMethod.GET)
    public Response<List<TBox>> queryTBoxList() {
        List<TBox> list = tBoxService.queryTBoxList();
        return Response.success(list);
    }

    /**
     * 复制箱子
     */
    @PreAuthorize("@ss.hasPermi('cs:box:boxListBackCount')")
    @ApiOperation("复制箱子")
    @RequestMapping(name = "复制箱子", value = "copyTbox", method = RequestMethod.POST)
    public Response<List<TBox>> copyTbox(@ApiParam(name = "boxIds", value = "箱子ID集合", required = true)
                                         @RequestBody List<String> boxIds) {
        if(CollectionUtils.isEmpty(boxIds)){
            return Response.fail("请选择需要复制的箱子");
        }
        return tBoxService.copyBox(boxIds);
    }

    /*---------------------------------------------前端接口-----------------------------------*/
    /**
     * 根据箱子ID获取对应的饰品列表
     * @param tBoxN     * @return
     */
    @ApiOperation("web根据箱子ID获取对应的饰品列表")
    @RequestMapping(name="根据箱子ID获取对应的饰品列表",value="common/goodsListByBoxId",method = RequestMethod.GET)
    @ApiImplicitParam(name = "boxId",value = "箱子ID" ,dataType = "String", paramType = "query", required = false)
    @Cacheable(value="twoSecondsCache", key="'goodsListByBoxId'+#p0")
    public Response<Map> goodsListByBoxId(String boxId)
    {
        try {
            /*获取登录用户*/
            LoginUser loginUser = tokenService.getLoginUserWeb(ServletUtils.getRequest());
            String userId = null;
            if(loginUser != null){
                SysUser sysUser = loginUser.getUser();
                userId = sysUser.getLoginUserId();
            }
            List<TGoods> list  = tBoxService.goodsListByBoxId(boxId);
            List<Map> goodsChanceList  = tBoxService.goodsChance(boxId);
            TBox box = tBoxService.getInfoTbox(boxId);
            if(box == null){
                return null;
            }
            if (list != null && list.size()>0) {
                box.setGoodsPic(list.get(0).getGoodsPic());
                list.forEach(bean -> {
                    JSONObject jsonObject = JSON.parseObject(bean.getRollValueRange());
                    bean.setRollValueRangeObj(jsonObject);
                });
            }
            Map map = new HashMap();
            map.put("list",list);
            map.put("box",box);
            map.put("goodsChance",goodsChanceList);
            map.put("freeOpenNum",0);
            if(userId != null){
                if(Constants.BOXTYPE5.equals(box.getBoxType())){
                    BigDecimal todayCzMoney = tRechargeMapper.selectTheDayCzCountByUserId(userId);
                    if(box.getEveryRecharge().compareTo(todayCzMoney) <= 0){
                        long opennum = backpackMapper.countErveryNum(Constants.GOOGSBLTYPE13,box.getBoxId());
                        if(opennum == 0){
                            map.put("freeOpenNum",1);
                        }
                    }
                }else if(Constants.BOXTYPE6.equals(box.getBoxType())){
                    /**战令箱子*/
                    Long warBoxNum = tWarReceiveMapper.tWarBoxNum(userId,boxId);
                    map.put("freeOpenNum",warBoxNum);
                }
            }
           return Response.success(map);
        } catch (Exception e) {
            log.error("根据箱子ID获取对应的饰品列表异常:{}",e.getMessage());
            return Response.fail(e.getMessage());
        }
    }

    /**
     * 开箱
     * @param userId 用户ID
     * @param boxId 箱子ID
     * @param num 开箱次数
     * @return
     */
    @CheckSwitch
    @ApiOperation("web开箱")
    @RequestMapping(name="开箱",value="unpacking",method = RequestMethod.GET)
    @Log(title = "箱子信息开箱", businessType = BusinessType.OTHER)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "boxId",value = "箱子ID" , dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "num",value = "数量" , dataType = "Integer", paramType = "query", required = true),
    })
    public Response<List<TGoods>> unpacking(@RequestParam(value = "boxId",required = true) String boxId,
                                            @RequestParam(value = "num",required = true) Integer num) {
        try {
            String userId = tokenService.getLoginUserId();
            return tBoxService.openBoxHash(userId, boxId, num);
        } catch (Exception e) {
            log.error("开箱异常:{}", e.getMessage());
            return Response.fail(Constants.FAILCODE, e.getMessage());
        }
    }

    @ApiOperation("web查询箱子标题和箱子信息列表")
    @RequestMapping(name="查询箱子标题和箱子信息列表",value="common/boxList",method = RequestMethod.GET)
    @Cacheable(value="tenSecondsCache", key="'getBoxList'")
    public Response<Map> getBoxList(){
        return  tBoxService.getList();
    }


    @ApiOperation("web查询箱子标题和箱子信息列表")
    @RequestMapping(name="查询箱子标题和箱子信息列表",value="battleBoxList",method = RequestMethod.GET)
    @Cacheable(value="tenSecondsCache", key="'getBattleBoxList'+#p0+#p1")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "boxTitleId",value = "箱子标题ID" , dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "sortBy",value = "排序方式 0价格升序 1价格降序" , dataType = "String", paramType = "query", required = false),
    })
    public Response<List<TBox>> getBattleBoxList(String boxTitleId,String sortBy){
        List<TBox> battleBoxList = tBoxService.getBattleBoxList(Constants.BOXTYPE1, boxTitleId, sortBy);
        return  Response.success(battleBoxList);
    }

//    /**
//     * 查询限量箱子剩余次数
//     * @param
//     * @return
//     */
//    @ApiOperation("web获取限量箱子剩余次数")
//    @RequestMapping(name="web获取限量箱子剩余次数",value="common/remainingTimes",method = RequestMethod.GET)
//    @ApiImplicitParam(name = "boxId",value = "箱子ID" ,dataType = "String", paramType = "query", required = false)
//    public Response<Map> remainingTimes(String boxId) {
//        /*获取登录用户*/
//        LoginUser loginUser = tokenService.getLoginUserWeb(ServletUtils.getRequest());
//        String userId = null;
//        if (loginUser != null) {
//            SysUser sysUser = loginUser.getUser();
//            userId = sysUser.getLoginUserId();
//        }
//        Map<String, Integer> surplusMap = tBoxService.openableNum(userId, boxId);
//        Map map = new HashMap();
//        TBox tbox = tBoxService.getInfoTbox(boxId);
//
//        /*总次数限制*/
//        Integer totalIsLimit = 1;
//        if (tbox.getTotalNum() != null) {
//            /*是否限量 0是 1否*/
//            totalIsLimit = 0;
//        }
//        /*单用户限制*/
//        Integer singleIsLimit = 1;
//        if (tbox.getSingleUserNum() != null) {
//            /*是否限量 0是 1否*/
//            singleIsLimit = 0;
//        }
//        map.put("totalIsLimit", totalIsLimit);
//        map.put("singleIsLimit", singleIsLimit);
//
//        long surplusTotalNum = 0L;
//        if (tbox.getTotalNum() != null) {
//            map.put("totalNum", tbox.getTotalNum());
//            surplusTotalNum = tbox.getTotalNum() - surplusMap.get("surplusTotalNum");
//        }
//        long surplusSingleUserNum = 0L;
//        if (tbox.getSingleUserNum() != null) {
//            map.put("singleUserNum", tbox.getSingleUserNum());
//            /*剩余次数*/
//            surplusSingleUserNum = tbox.getSingleUserNum() - surplusMap.get("surplusSingleUserNum");
//        }
//        map.put("surplusSingleUserNum", surplusSingleUserNum);
//        map.put("surplusTotalNum", surplusTotalNum);
//        return Response.success(map);
//    }


//    @ApiOperation("积分盲盒和推广盲盒列表")
//    @RequestMapping(name="积分盲盒和推广盲盒列表",value="common/activityBoxList",method = RequestMethod.GET)
//    @Cacheable(value="tenSecondsCache", key="'activityBoxList'+#p0")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "boxType",value = "箱子类型 2 充值积分箱子 3 推广积分箱子" , dataType = "String", paramType = "query", required = true),
//    })
//    public Response<List<TBox>> activityBoxList(String boxType){
//        if (!("2".equals(boxType) || "3".equals(boxType))){
//            return  Response.success("参值错误！");
//        }
//        List<TBox> battleBoxList = tBoxService.activityBoxList(boxType);
//        return  Response.success(battleBoxList);
//    }

    @GetMapping("/common/open_box_hash_test_v")
    public Response openBoxHashTest(String userSeed,String boxId, int cs){
        return tBoxService.openBoxHashTest(userSeed,boxId,cs);
    }

    @GetMapping("/common/hash_test")
    public Response hashTest(String userSeed,int cs,int partitionSize){
        return tBoxService.hashTest(userSeed,cs,partitionSize);
    }
}
